import os
# import matplotlib.pyplot as plt

from flask import Flask, make_response, send_from_directory, request, jsonify, render_template
from flask_cors import CORS
import test
import hashlib
import random

app = Flask(__name__)
CORS(app, resources=r'/*')


# 127.0.0.1:5000/images

def cors_head(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,HEAD,GET,POST'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with'
    return response


@app.route('/', methods=['POST', 'GET'])
def deal_with():
    if request.method == 'POST':
        file_dir = os.path.join('demo', 'edges2shoes')
        file = request.files.get('image')
        name = hashlib.md5(str(random.random()).encode()).hexdigest()
        file.save(os.path.join(file_dir, f'{name}.jpg'))  # 这里也改一下 不然会把之前的图片覆盖掉
        test.generate(mode='edges2shoes')
        address_list = [f'/static/results/edges2shoes_pix2pix/test_latest/images/{name}_fake.png',]
        response = make_response(jsonify(address_list))
        print(address_list)
        response = cors_head(response)
        return response

    return render_template('index.html')


@app.route('/images', methods=['GET'])
def get_image():
    args = request.args
    path = args.get("path")
    sep = path.rindex(os.sep)
    directory = path[:sep]
    file_name = path[sep + 1:]
    response = make_response(send_from_directory(directory, file_name, as_attachment=True))
    response = cors_head(response)
    print(1)
    return response


if __name__ == '__main__':
    app.run(host="127.0.0.1")
